package es.udc.fic.hamNeggs.web;

import org.apache.log4j.Logger;

import es.udc.fic.hamNeggs.dao.InputProject;
import es.udc.fic.hamNeggs.dao.InputUser;
import es.udc.fic.hamNeggs.manager.ProjectManager;
import es.udc.fic.hamNeggs.manager.UserManager;
import es.udc.fic.hamNeggs.manager.WorksManager;
import es.udc.fic.hamNeggs.pojo.Project;
import es.udc.fic.hamNeggs.pojo.User;
import es.udc.fic.hamNeggs.pojo.Works;
import es.udc.fic.hamNeggs.pojo.Works.Rol;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.List;

/**
 * Servlet implementation class ProjectDetails
 */
public class ProjectDetails extends HttpServlet {
    private static final long   serialVersionUID = 1L;
    private final static Logger LOG              = Logger.getLogger(ProjectDetails.class.getName());

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProjectDetails() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final UserManager usrmng = new UserManager();
        final List<User> users = usrmng.getUserList();

        final ArrayList<InputUser> iUsers = new ArrayList<InputUser>();

        for (final User user : users) {
            final InputUser iUser = new InputUser();
            iUser.setUser(user);
            iUsers.add(iUser);
        }

        request.setAttribute("users", iUsers);

        usrmng.close();

        if (request.getParameter("newUser") != null)
            request.getRequestDispatcher("/user_detail.jsp").forward(request, response);
        if (request.getParameter("newProject") != null)
            request.getRequestDispatcher("/project_detail.jsp").forward(request, response);

        if ((request.getParameter("usrid") != null && request.getParameter("usrid") != "")
                || (request.getAttribute("usrid") != null && request.getAttribute("usrid").toString() != "")) {
            final UserManager usrmngu = new UserManager();
            final InputUser user = new InputUser();
            User useru = null;
            if (request.getParameter("usrid") != null && request.getParameter("usrid") != "")
                useru = usrmngu.getUser(new Long(request.getParameter("usrid")));
            if (request.getAttribute("usrid") != null && request.getAttribute("usrid").toString() != "")
                useru = usrmngu.getUser(new Long(request.getAttribute("usrid").toString()));

            user.setUser(useru);
            request.setAttribute("selectUser", user);
            usrmngu.close();

            request.getRequestDispatcher("/user_detail.jsp").forward(request, response);
        }

        if ((request.getParameter("prjid") != null && request.getParameter("prjid") != "")
                || (request.getAttribute("prjid") != null && request.getAttribute("prjid").toString() != "")) {
            final ProjectManager prjmng = new ProjectManager();
            final InputProject project = new InputProject();
            Project projectu = null;
            if (request.getParameter("prjid") != null && request.getParameter("prjid") != "")
                projectu = prjmng.getProject(new Long(request.getParameter("prjid")));
            if (request.getAttribute("prjid") != null && request.getAttribute("prjid").toString() != "")
                projectu = prjmng.getProject(new Long(request.getAttribute("prjid").toString()));
            project.setProject(projectu);
            request.setAttribute("selectProject", project);
            prjmng.close();

            request.getRequestDispatcher("/project_detail.jsp").forward(request, response);
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final UserManager usrmng = new UserManager();
        final ProjectManager prjmng = new ProjectManager();
        final WorksManager wrkmng = new WorksManager();

        try {
            switch (request.getParameter("action")) {
                case "AddProject":
                    final InputProject project = new InputProject();
                    if (request.getParameter("dateStart") != "")
                        project.setDateStart(request.getParameter("dateStart"));
                    if (request.getParameter("dateEnd") != "")
                        project.setDateEnd(request.getParameter("dateEnd"));
                    if (request.getParameter("name") != "")
                        project.setName(request.getParameter("name"));

                    final Project actualProject = project.toProject();
                    final User scrumMaster = usrmng.getUser(new Long(request.getParameter("scrumMaster")));
                    prjmng.saveProject(actualProject);

                    final Works works = new Works();
                    works.setUser(scrumMaster);
                    works.setProject(actualProject);
                    works.setRol(Rol.ScrumMaster);
                    works.setDateStart(new Date(Calendar.getInstance().getTimeInMillis()));
                    wrkmng.saveWorks(works);
                    break;
                case "UpdateProject":
                    final Project actualProjectu = prjmng.getProject(new Long(request.getParameter("prjid")));
                    if (request.getParameter("dateStart") != "")
                        actualProjectu.setDateStart(Date.valueOf(request.getParameter("dateStart")));
                    if (request.getParameter("dateEnd") != "")
                        actualProjectu.setDateEnd(Date.valueOf(request.getParameter("dateEnd")));
                    if (request.getParameter("name") != "")
                        actualProjectu.setName(request.getParameter("name"));
                    prjmng.updateProject(actualProjectu);
                    break;
                case "UpdateUser":
                    final User actualUseru = usrmng.getUser(new Long(request.getParameter("usrid")));
                    if (request.getParameter("name") != "")
                        actualUseru.setName(request.getParameter("name"));
                    if (request.getParameter("fullName") != "")
                        actualUseru.setFullName(request.getParameter("fullName"));
                    usrmng.updateUser(actualUseru);
                    break;
                case "AddUser":
                    final InputUser user = new InputUser();
                    user.setPassword(org.springframework.util.DigestUtils.md5DigestAsHex(request.getParameter("name").getBytes()));
                    user.setName(request.getParameter("name"));
                    user.setFullName(request.getParameter("fullName"));

                    final User actualUser = user.toUser();
                    usrmng.saveUser(actualUser);
                    break;
                default:
                    break;

            }
        } catch (Exception e) {
            String error = "[";
            Enumeration<String> names = request.getParameterNames();
            while (names.hasMoreElements()) {
                final String paramName = names.nextElement();
                final String paramValue = request.getParameter(paramName);
                error = error.concat(paramName + ":" + paramValue + ";");
            }
            error = error.concat("]");
            LOG.error("Error while executing action: " + request.getParameter("action")
                    + "with params: " + error + "\n"
                    , e);
        }

        usrmng.close();
        prjmng.close();
        wrkmng.close();

        doGet(request, response);

    }

}
